package com.firmboy.io.nio;

import com.firmboy.tool.PathTool;
import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO测试练习类
 *
 * @author firmboy
 * @create 2018-04-28 上午10:19
 **/
public class NIOTest {



    @Test
    public void FileChannelTest1() throws IOException {

        RandomAccessFile rw = new RandomAccessFile("/firmboy/workspace/test/test.txt", "rw");
        FileChannel channel = rw.getChannel();
        while(true){
            ByteBuffer buf = ByteBuffer.allocate(48);
            int l = channel.read(buf);
            if(l==-1){
                break;
            }
            System.out.println(l);
            System.out.println(new String(buf.array(),"utf-8"));

        }



    }

    @Test
    public void FileChannelTest() throws IOException {
        String path = "/firmboy/workspace/test/";
        path = path+"test.txt";
        System.out.println(path);
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);

        BufferedReader bfr = new BufferedReader(new FileReader(file));
        bfr.readLine();




        FileChannel channel = fis.getChannel();
        while(true){
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int read = channel.read(buf);
            System.out.println("read:"+read);
            if(read==-1){
                break;
            }

            for (int i = 0;i<buf.array().length;i++){
                System.out.println("i:"+buf.array()[i]);
            }



            System.out.println(new String(buf.array(),"utf-8"));




        }

    }



}
